package com.michael.starter.advise;

import com.michael.common.error.code.BizCode;
import com.michael.common.error.exception.BizException;
import com.michael.common.result.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestControllerAdvice
@Slf4j
public class ExceptionAdvise {

    @ExceptionHandler(Exception.class)
    public BaseResult<Object> handlerBusinessException(HttpServletRequest httpRequest, HttpServletResponse response, Exception e) {
        BaseResult<Object> baseResult = BaseResult.successOf(null);
        if (e instanceof IllegalArgumentException) {
            baseResult.setRet(BizCode.PARAMETER_ERR.getRet());
            baseResult.setMsg(BizCode.PARAMETER_ERR.getMsg());
        } else if (e instanceof BizException) {
            BizException bizException = (BizException) e;
            baseResult.setRet(bizException.getRet());
            baseResult.setMsg(bizException.getMsg());
        } else {
            baseResult.setRet(BizCode.SYS_FATAL_ERR.getRet());
            baseResult.setMsg(BizCode.SYS_FATAL_ERR.getMsg());
        }
        return baseResult;
    }

}
